package com.jixuian.rabbitmq.task;

import com.jixuian.rabbitmq.po.TransMessagePO;
import com.jixuian.rabbitmq.service.TransMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
@Configuration
@EnableScheduling
public class ResendTask {

    @Autowired
    private TransMessageService transMessageService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${mq.resendTimes}")
    private Integer resendTimes;

    @Scheduled(fixedDelayString = "${mq.resendFreq}")
    public void resendMessage() {
        log.info("resendMessage() invoke");
        List<TransMessagePO> pos = transMessageService.listReadyMessages();
        log.info("resendMessage(), pos:{}", pos);

        for (TransMessagePO po : pos) {
            log.info("resendMessage(), po:{}", po);
            if (po.getSequence() > resendTimes) {
                log.error("resend too many times");
                transMessageService.messageDead(po.getId());
                continue;
            }

            MessageProperties messageProperties = new MessageProperties();
            messageProperties.setContentType("application/json");
            messageProperties.setMessageId(po.getId());

            Message message = new Message(po.getPayload().getBytes(), messageProperties);
            // 把消息持久化的id放入CorrelationData, 消息返回时会带回
            rabbitTemplate.convertAndSend(po.getExchange(), po.getRoutingKey(), message, new CorrelationData(po.getId()));

            transMessageService.messageResend(po.getId());
        }
    }
}
